<template>
  <div>
    <a-button type="primary" style="margin-top: 20px" @click="editModal(0)">新建</a-button>
    <div style="margin-top: 20px">
      <a-table :pagination="false" :columns="columns" :data-source="data" rowKey="id">
      <span slot="state" slot-scope="state">
      <a-tag :color="state === -1 ? 'red' : 'cyan'">
        {{ state === -1 ? '禁用' : '使用中' }}
      </a-tag>
    </span>
    <span slot="action" slot-scope="text, record">
      <a-button type="primary" icon="edit" size="small" @click="editModal(record)"></a-button>
      <a-divider type="vertical" />
      <a-dropdown>
        <a class="ant-dropdown-link" @click="e => e.preventDefault()">
      更多 <a-icon type="down" />
    </a>
    <a-menu slot="overlay">
      <a-menu-item>
        <a href="javascript:;">禁用</a>
      </a-menu-item>
      <a-menu-item>
        <a href="javascript:;" @click="roleEditModal(record)">角色管理</a>
      </a-menu-item>
    </a-menu>
  </a-dropdown>
    </span>
      </a-table>
      <div style="margin-top: 20px;text-align: center">
        <a-pagination v-model="current" :page-size="pageSize" :total="total" @change="changePage" />
      </div>
    </div>
    <div>
      <a-modal v-model="visible" title="编辑" @ok="handleOk">
        <a-form :form="form">

          <a-form-item>
            <a-input v-if="mdl.id > 0" v-decorator="['id', { initialValue: mdl.id } ]" hidden/>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="昵称">
            <a-input
              v-decorator="['nickname',{ initialValue: mdl.nickname },{rules: [{required: true,message: '请填写角色名称'}]}]"/>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="登录名称">
            <a-input
              v-decorator="['username',{ initialValue: mdl.username },{rules: [{required: true,message: '请填写登录名称'}]}]"/>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="登录密码">
            <a-input
              v-decorator="['credential']"/>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="父级"
          >
            <a-select v-decorator="['merchantId',{initialValue: mdl.merchantId}]">
              <a-select-option :value="0">所属商户</a-select-option>
              <a-select-option v-for="(item, index) in parentMerchants" :value="item.id" :key="index">{{ item.merchantName }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="email">
            <a-input
              v-decorator="['email',{ initialValue: mdl.email }]"/>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="手机号码">
            <a-input
              v-decorator="['mobile',{ initialValue: mdl.mobile }]"/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="类型"
            hasFeedback
          >
            <a-select v-decorator="['state', { initialValue: mdl.state}]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="-1">禁用</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="状态"
            hasFeedback
          >
            <a-select v-decorator="['state', { initialValue: mdl.state}]">
              <a-select-option :value="1">正常</a-select-option>
              <a-select-option :value="-1">禁用</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="备注"
            hasFeedback
          >
            <a-textarea
              :rows="5"
              placeholder="..."
              id="remark"
              v-decorator="['remark', {initialValue: mdl.remark}]"
            />
          </a-form-item>

        </a-form>
      </a-modal>
    </div>
    <div>
      <a-modal :bodyStyle="{'width':'1000px'}" v-model="roleVisible" title="角色修改" @ok="handleRoleOk" @cancel="handleRoleCancel">
        <template>
            <div class="check-box" v-for="(item, index) in roles">
              <input type="checkbox" :value="item.id" :checked="item.check"  @change="checkRole(index)">
              <span style="cursor:pointer;" @click="checkRole(index)">{{ item.roleName }}</span>
          </div>
        </template>
      </a-modal>
    </div>
  </div>
</template>

<script>
  import { getSysUserList, saveUpdateSysUser, getMerchantList } from "@/api/system";
  import {getRoleList, saveUserRoles} from "../../api/system";
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '昵称',
      key: 'nickname',
      dataIndex: 'nickname',
    },
    {
      title: '登录名',
      key: 'username',
      dataIndex: 'username',
    },
    {
      title: '所属商户',
      dataIndex: 'merchantName',
      key: 'merchantName',
    },
    {
      title: '手机号',
      key: 'mobile',
      dataIndex: 'mobile',
    },
    {
      title: '邮箱',
      key: 'email',
      dataIndex: 'email',
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      scopedSlots: { customRender: 'state' },
    },
    {
      title: '操作',
      key: 'action',
      scopedSlots: { customRender: 'action' },
    },
  ];
  export default {
    name: "SysUserList",
    data() {
      return {
        visible: false,
        roleVisible: false,
        data: [],
        current: 1,
        columns,
        pageSize: 15,
        total: 0,
        mdl: {
          id: 0,
          nickname: '',
          username: '',
          credential: '',
          email: '',
          mobile: '',
          state: 1,
          remark: '',
          merchantId: 0
        },
        parentMerchants: [],
        form: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 12 }
        },
        currentUserId: 0,
        roles: [],
        roleChecked: []
      }
    },
    mounted() {
      this.getSysUserDataList()
    },
    methods: {
      changePage() {
        this.data= []
        this.getSysUserDataList();
      },
      async getSysUserDataList() {
        let params = {
          pageNo: this.current,
          pageSize: this.pageSize
        }
        const result = await getSysUserList(params)
        const pageInfo = result.data.page
        this.total = pageInfo.totalPage
        this.data = pageInfo.list
      },
      async merchantList() {
        const result = await getMerchantList({pageNo:1,pageSize:100})
        let pageInfo = result.data.page
        this.parentMerchants = pageInfo.list
      },
      editModal(record) {
        this.mdl = Object.assign({}, record === 0 ? this.mdl : record)
        this.merchantList()
        this.form = this.$form.createForm(this)
        this.visible = true
      },
      handleOk() {
        this.form.validateFields(async (err, values) => {
          const result = await saveUpdateSysUser(values)
          if (result.code > 0) {
            this.$ms('保存成功')
            this.form = this.$form.createForm(this)
            this.visible = false
            this.getSysUserDataList()
          } else {
            this.$me(result.message)
          }
        })
      },
      roleEditModal(record) {
        this.currentUserId = 0
        this.roleAllList(record.userRoles)
        this.currentUserId = record.id
        this.roleVisible = true
      },
      checkRole(index) {
        this.roleChecked = []
        this.$set(this.roles[index], 'check', !this.roles[index].check)
        this.roles.map(item => {
          if (item.check) this.roleChecked.push(item.id)
        })
      },
      async roleAllList(userRoles) {
        const result = await getRoleList({pageNo: 1, pageSize: 100})
        let pageInfo = result.data.page
        this.roles = pageInfo.list
        for (let i = 0; i < this.roles.length; i++) {
          let index = userRoles.findIndex(ele =>{ return ele.roleId === this.roles[i].id })
          if (index > -1) this.roles[i].check = true
        }
      },
      async handleRoleOk() {
        if (this.currentUserId <=0) {
          this.$me("参数错误")
          this.roleVisible = false
          return
        }
        const result = await saveUserRoles({ userId: this.currentUserId, roleIds: this.roleChecked})
        if (result.code > 0) {
          this.$ms("保存成功")
          this.roleVisible = false
        } else {
          this.$me("保存失败")
        }
      },
      handleRoleCancel() {

      }
    }
  }
</script>

<style scoped>
  .check-box{
    margin-top: 10px;
    display: inline-block;
    box-sizing: border-box;
    cursor: pointer;
    position: relative;
    padding-left: 25px;
    padding-right: 20px;
  }
</style>
